package com.mypog;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/CheckUser")
public class CheckUser extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Response.
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();

		// Get user session.
		String account = request.getParameter("account");

		request.getSession().setAttribute("username", account);
		// Get player and his enemy objects.
		AllUsers allusers = new AllUsers();
		User player = allusers.getUserObject(account, "user");
		User enemy = allusers.playingUsersEnemy(account);

		// Check user session.
		if (account == null || account == "") {
			// No user, will be redirected to login page.
			out.print("");
		} else if (player != null && enemy != null) {
			// User has refreshed the page. Update the enemy.
			enemy.setEnemy("KASUTAJA LAHKUS");
			player.reset();
			out.print(account + "," + player.getWon() + "," + player.getLost());
		} else if (player == null) {
			checkDB(account, player, out);
		}
	}
	
	// Check DB for user, if no such user, create.
	private void checkDB(String account, User player, PrintWriter out) {
		// Create MySQL connection.
		MySQLDb sql = new MySQLDb();

		// Check DB for user.
		String answer = sql.getSqlOneValue("SELECT * FROM Users", "Name");

		if (answer.contains(account)) {
			String query = sql.getSqlQuery("SELECT * FROM Users WHERE Name = '"
					+ account + "'", "Won", "Lost");

			// Add new user.
			AllUsers.accounts.put(account, new User(account));

			String[] queryResponse = query.split(",");

			// Set query response.
			player = AllUsers.accounts.get(account);
			player.setWon(queryResponse[0]);
			player.setLost(queryResponse[1]);
		} else {
			// No user in DB, make a new one.
			AllUsers.accounts.put(account, new User(account));
			sql.setSqlQyery("INSERT INTO Users(Name) VALUES ('" + account
					+ "')");
		}
		out.print(account + "," + player.getWon() + "," + player.getLost());
	}
}
